import CONST from '../const'

/**
 * 获取地图入口位置，此属性存储在地图属性中.
 *
 * @param {Phaser.Tilemaps.Tilemap} map the map object
 * @returns {object} e.g. { x: 111, y: 111 }
 */
function getMapEnterPos (map) {
  const pos = {}
  map.properties.forEach((prop) => {
    if (prop.name === CONST.MAP_PRO_ENTER_POS_X) {
      pos.x = prop.value
    }
    if (prop.name === CONST.MAP_PRO_ENTER_POS_Y) {
      pos.y = prop.value
    }
  })
  if (!pos.x) {
    // eslint-disable-next-line no-console
    console.error('Magic Tower - enterPosX not set in map property!', map)
  }
  if (!pos.y) {
    // eslint-disable-next-line no-console
    console.error('Magic Tower - enterPosY not set in map property!', map)
  }

  pos.x = parseInt(pos.x, 10)
  pos.y = parseInt(pos.y, 10)

  // index based 1, origin at center
  pos.x = (pos.x - 1) * CONST.BLOCK_SIZE + CONST.BLOCK_SIZE / 2
  pos.y = (pos.y - 1) * CONST.BLOCK_SIZE + CONST.BLOCK_SIZE / 2

  return pos
}

/**
 * 获取地图出口位置，此属性存储在地图属性中.
 *
 * @param {Phaser.Tilemaps.Tilemap} map
 * @returns {object} e.g. { x: 111, y: 111 }
 */
function getMapLeavePos (map) {
  const pos = {}
  map.properties.forEach((prop) => {
    if (prop.name === CONST.MAP_PRO_LEAVE_POS_X) {
      pos.x = prop.value
    }
    if (prop.name === CONST.MAP_PRO_LEAVE_POS_Y) {
      pos.y = prop.value
    }
  })
  if (!pos.x) {
    // eslint-disable-next-line no-console
    console.error('Magic Tower - leavePosX not set in map property!', map)
  }
  if (!pos.y) {
    // eslint-disable-next-line no-console
    console.error('Magic Tower - leavePosY not set in map property!', map)
  }

  pos.x = parseInt(pos.x, 10)
  pos.y = parseInt(pos.y, 10)

  // index based 1, origin at center
  pos.x = (pos.x - 1) * CONST.BLOCK_SIZE + CONST.BLOCK_SIZE / 2
  pos.y = (pos.y - 1) * CONST.BLOCK_SIZE + CONST.BLOCK_SIZE / 2

  return pos
}

/**
 * 画出指定点的位置
 * @param {Phaser.Scene} scene
 * @param {number} x
 * @param {number} y
 */
function drawPoint (scene, x, y) {
  // track target position
  scene.add.graphics().lineStyle(2, 0xFF0000, 1.0)
  scene.add.graphics().fillStyle(0xFF0000, 1.0)
  const size = 4
  scene.add.graphics().fillRect(x - size / 2, y - size / 2, size, size)
}

export default {
  getMapEnterPos,
  getMapLeavePos,
  drawPoint
}
